All files / src/app/api/collections/[id]/photos/reassign route.ts

100% Statements 29/29
100% Branches 19/19
100% Functions 2/2
100% Lines 25/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62                              14x 14x 14x 1x     13x   13x 13x     10x 10x   1x   9x 14x     59x   1x   8x 1x           7x   14x 6x 5x 3x   4x 4x 3x   1x      
import { NextResponse } from "next/server";
import { getSession } from "@/lib/auth";
import { getDb } from "@/lib/db";
import { requireApiCapability } from "@/server/dal/collection-access";
import {
  ItemService,
  MAX_GROUP_PHOTOS,
  type ReassignDest,
} from "@/server/services/ItemService";
import { POOL_CAP_MESSAGE } from "@/lib/pool-limits";
import { errorResponse } from "@/server/api/http-errors";
 
// Unified "Move to…": reassigns selected photos to an existing item, a new item,
// or back to the pool. photos:write = curator (full-curator model).
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const session = await getSession();
  if (!session?.user) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }
 
  const db = getDb();
  // photos:write = curator — any curator may reassign photos (full-curator model).
  const access = await requireApiCapability(db, id, session.user.id, "photos:write");
  if (access instanceof NextResponse) return access;
 
  let body: unknown;
  try {
    body = await req.json();
  } catch {
    return NextResponse.json({ error: "Invalid body" }, { status: 400 });
  }
  const photoIds = (body as { photoIds?: unknown })?.photoIds;
  if (
    !Array.isArray(photoIds) ||
    photoIds.length === 0 ||
    !photoIds.every((x) => typeof x === "string")
  ) {
    return NextResponse.json({ error: "photoIds must be a non-empty string array" }, { status: 400 });
  }
  if (photoIds.length > MAX_GROUP_PHOTOS) {
    return NextResponse.json(
      { error: POOL_CAP_MESSAGE },
      { status: 400 },
    );
  }
 
  const d = (body as { destination?: any })?.destination;
  let dest: ReassignDest;
  if (d?.type === "item" && typeof d.itemId === "string") dest = { type: "item", itemId: d.itemId };
  else if (d?.type === "new") dest = { type: "new" };
  else if (d?.type === "pool") dest = { type: "pool" };
  else return NextResponse.json({ error: "Invalid destination" }, { status: 400 });
 
  try {
    const result = await ItemService.fromDb(db).reassignPhotos(id, photoIds as string[], dest);
    return NextResponse.json({ number: result.number }, { status: 200 });
  } catch (error) {
    return errorResponse(error);
  }
}